<?php
// Conjunto de funções para inserir/excluir usuários da lista de email
// Criado por Paulo Geyer <paulogeyer@gmail.com>

function NewsletterConecta() {
  $link_news = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
  mysql_select_db(PHPLIST_DB_NAME);
}

function NewsletterChecaUsuario($email) {
  NewsletterConecta();
  $res = mysql_query('select id from phplist_user_user where email = "'.$email.'"');
  if ($user = mysql_fetch_object($res)) {
    return $user->id;
  } else {
    return false;
  }
}

function NewsletterCriaUsuario($email) {
  NewsletterConecta();
  if(!NewsletterChecaUsuario($email)) {
    $uniq_id = md5(uniqid(mt_rand(0,1000).$email));
    $sql = 'insert into phplist_user_user(email,confirmed,entered,modified,uniqid,htmlemail) values("'.$email.'",1, CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,"'.$uniq_id.'",1)';
    mysql_query($sql);
    return NewsletterChecaUsuario($email);
  }
}

function NewsletterUsuarioAssinaLista($email,$lista_id) {
  NewsletterConecta();
  if ($id = NewsletterChecaUsuario($email)) {
    $res = mysql_query('select * from listuser where userid = '.$id.' AND listid = '.$lista_id);
    if (mysql_num_rows($res) > 0) {
      return $id;
    } else {
      return false;
    }
  } else {
    return false;
  }
}

function NewsletterUsuarioIncluiLista($email,$lista_id) {
  NewsletterConecta();
  if(!($user_id = NewsletterChecaUsuario($email))) {
    NewsletterCriaUsuario($email);
    $user_id = NewsletterChecaUsuario($email);
  }

  if(!NewsletterUsuarioAssinaLista($email,$lista_id)) {
    return mysql_query('insert into listuser(userid,listid,entered,modified) values('.$user_id.','.$lista_id.', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)');
  } else {
    return false;
  }
}

function NewsletterUsuarioExcluiLista($email,$lista_id) {
  NewsletterConecta();
  if (($user_id = NewsletterChecaUsuario($email)) && NewsletterUsuarioAssinaLista($email,$lista_id)) {
    mysql_query('delete from listuser where userid = '.$user_id.' AND listid = '.$lista_id);
  }
}
